package com.bwsoft.api.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.bwsoft.api.pojo.ResponsePojo;
import com.bwsoft.api.service.DictionaryService;
import com.bwsoft.api.util.Constant;
import com.bwsoft.domain.Dictionary;
import com.bwsoft.domain.DictionaryData;

@Service(DictionaryService.NAME)
public class DictionaryServiceImpl extends BaseServiceImpl implements
		DictionaryService {
	private static Logger LOG = Logger.getLogger(DictionaryServiceImpl.class);

	@SuppressWarnings("unchecked")
	@Override
	public ResponsePojo getData(String dicName) {

		ResponsePojo rp=new ResponsePojo();
		
		List<Map<String, Object>> returnMap=new ArrayList<Map<String, Object>>();
		try{
			String [] dic=dicName.split(",");
			dicName="";
			LOG.info("需要查找的dicName共有"+dic.length+"条");
			for (String string : dic) {
				dicName +="'"+string+"',";
			}
			String hql="from Dictionary as d where d.dicName in ("+dicName.substring(0,dicName.length()-1)+")";
			
			List<Dictionary> dataList= dictionaryDao.findByHql(hql);
			
			returnMap=createMap(dataList);
			
		}catch (Exception e) {
			e.printStackTrace();
			LOG.info("异常"+e.getStackTrace());
			rp.setErrcode(50000);
			rp.setErrmsg("服务器异常");
			rp.setData(e.toString());
			return rp;
		}
		rp.setErrcode(0);
		rp.setErrmsg("请求成功");
		rp.setData(returnMap);
		return rp;
	}

	private List<Map<String, Object>> createMap(List<Dictionary> dataList) {
		List<Map<String, Object>> returnList = new ArrayList<Map<String, Object>>();
		for (Dictionary dictionary : dataList) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("dicName", dictionary.getDicName());
			List<Map<String, Object>> ddList = new ArrayList<Map<String, Object>>();
			for (DictionaryData dd : dictionary.getDictionaryDatas()) {
				Map<String, Object> ddmap = new HashMap<String, Object>();
				ddmap.put("dicKey", dd.getDicKey());
				ddmap.put("dicValue", dd.getDicValue());
				ddList.add(ddmap);
			}
			map.put("dicData", ddList);
			returnList.add(map);
		}
		return returnList;
	}


}
